/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gestionnaires;

import utilisateurs.modeles.Film;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import utilisateurs.modeles.Tag;
import java.util.Collection;

@Stateless
public class GestionnaireTags extends AbstractFacade<Tag> {
    @PersistenceContext(unitName = "BlueRayPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public GestionnaireTags() {
        super(Tag.class);
    }

    public Tag getByName(String name) {
        Query query = em.createQuery("SELECT t FROM Tag t WHERE t.nom = :name");
        query.setParameter("name", name);

        try {
            return (Tag) query.getSingleResult();
        } catch(NoResultException e) {
            return null;
        }
    }

    public Tag getOrCreate(String name) {
        Tag tag = getByName(name);

        if (tag == null) {
            tag = new Tag(name);
            create(tag);
        }

        return tag;
    }

    public Collection<Tag> getAll() {
        Query q = em.createQuery("SELECT t FROM Tag t ORDER BY t.nom");
        return q.getResultList();
    }

    public Collection<Tag> getByVideoGameID(int id) {
        Query q = em.createQuery("SELECT t FROM JeuVideo jv, IN(jv.tags) t WHERE jv.id = :id");
        q.setParameter("id", id);
        return q.getResultList();
    }

    public Collection<Tag> getByKeyword(String keyword) {
        Query q = em.createQuery("SELECT t FROM Tag t WHERE LOWER(t.nom) LIKE :keyword ORDER BY t.nom");
        q.setParameter("keyword", "%" + keyword.toLowerCase() + "%");
        return q.getResultList();
    }

    public Collection<String> getNames() {
        Query q = em.createQuery("SELECT DISTINCT t.nom FROM Tag t ORDER BY t.nom");
        return q.getResultList();
    }
}
